import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.http.WebSocket;
import java.nio.charset.StandardCharsets;

public class SimpleHttpServer {
    public static void main(String[] args) throws IOException {
        // 创建服务器套接字，监听 8080 端口
        ServerSocket serverSocket = new ServerSocket(8080);
        System.out.println("服务器启动，监听端口 8080...");

        // 无限循环接收客户端连接
        while (true) {
            // 等待客户端连接（阻塞方法）
            Socket clientSocket = serverSocket.accept();
            System.out.println("客户端连接成功：" + clientSocket.getInetAddress());

            // 处理客户端请求
            handleRequest(clientSocket);

            // 关闭客户端连接
            clientSocket.close();
        }
    }
    private static void handleRequest(Socket clientSocket) {
        try {
            // 获取输入流（读取客户端请求）,读取文本要用字符流
            BufferedReader in = new BufferedReader(
                    new InputStreamReader(clientSocket.getInputStream()));

            // 获取输出流（发送响应给客户端）
            OutputStream out = clientSocket.getOutputStream();

            // 读取请求行（例如：GET / HTTP/1.1）
            String requestLine = in.readLine();
            System.out.println(requestLine);
            String[] parts = requestLine.split(" ");
            String method = parts[0];

            String path = parts[1];

            // 忽略请求头（读取直到空行）
            String line;
            while ((line = in.readLine()) != null && !line.isEmpty()) {
                // 不做处理，直接忽略
            }
            // 根据路径返回不同内容
            String content;
            if (path.equals("/")) {
                content = "<h1>Hello World</h1>";
            } else if (path.equals("/time")) {
                content = String.valueOf(System.currentTimeMillis());
            } else {
                content = "<h1>404 Not Found</h1>";
            }

            // 构建 HTTP 响应
            String response = "HTTP/1.1 200 OK\r\n" +
                    "Content-Type: text/html\r\n" +
                    "Content-Length: " + content.getBytes().length + "\r\n" +
                    "Connection: close\r\n" +
                    "\r\n" +
                    content;

            // 发送响应给客户端
            out.write(response.getBytes(StandardCharsets.UTF_8));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}